package com.bocai.kelala.ui.travel.set.act;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.bocai.kelala.App;
import com.bocai.kelala.R;
import com.bocai.kelala.base.BaseActivity;
import com.bocai.kelala.bean.UploadImgBean;
import com.bocai.kelala.bean.UserBean;
import com.bocai.kelala.ui.travel.main.act.MainActivity;
import com.bocai.kelala.ui.travel.set.contract.SetContract;
import com.bocai.kelala.ui.travel.set.module.PwSetModule;
import com.bocai.kelala.ui.travel.set.module.SetModule;
import com.bocai.kelala.ui.travel.set.presenter.SetPresenter;
import com.bocai.kelala.util.DataCleanManager;
import com.bocai.kelala.util.SP;
import com.bocai.kelala.widget.AlertDialog;
import com.bumptech.glide.Glide;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import me.iwf.photopicker.PhotoPicker;

/**
 * Created by yuanfei on 2017/6/12.
 */

public class SetActivity extends BaseActivity implements SetContract.view{
    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.right_btn)
    Button rightBtn;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.textView)
    TextView textView;
    @BindView(R.id.head_img)
    CircleImageView headImg;
    @BindView(R.id.ll_my_avatar)
    LinearLayout llMyAvatar;
    @BindView(R.id.tv_proof_type)
    TextView tvProofType;
    @BindView(R.id.ll_proof_info)
    LinearLayout llProofInfo;
    @BindView(R.id.tv_change_phone)
    TextView tvChangePhone;
    @BindView(R.id.ll_change_phone)
    LinearLayout llChangePhone;
    @BindView(R.id.ll_pw_set)
    LinearLayout llPwSet;
    @BindView(R.id.ll_car_term)
    LinearLayout llCarTerm;
    @BindView(R.id.ll_about_app)
    LinearLayout llAboutApp;
    @BindView(R.id.textView5)
    TextView textView5;
    @BindView(R.id.ll_clear_cache)
    LinearLayout llClearCache;
    @BindView(R.id.ll_exit)
    LinearLayout llExit;
    TimePickerView pickerView;
    @BindView(R.id.ll_back)
    LinearLayout llBack;
    @Inject
    SetPresenter presenter;
    String imgUrl;
    UploadImgBean uploadImgBean;
    String totalCacheSize;
    @BindView(R.id.tv_clear_cache)
    TextView tvClearCache;

    @Override
    public int getLayoutId() {
        return R.layout.act_set;
    }

    @Override
    public void initPresenter() {
        App.get(this).getAppComponent().addSub(new SetModule(this)).inject(this);
    }

    @Override
    public void initView() {
        initToolbar("设置");
        initBack(imgBack,llBack);
        presenter.getUser();
        try {
            totalCacheSize = DataCleanManager.getTotalCacheSize(this);
            if ("0.00MB".equals(totalCacheSize)) {
                totalCacheSize = "0.00MB";
            }
            tvClearCache.setText(totalCacheSize);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    @OnClick({R.id.ll_my_avatar,R.id.ll_change_phone,R.id.ll_exit,R.id.ll_pw_set,R.id.ll_proof_info,R.id.ll_about_app,R.id.ll_car_term,R.id.ll_clear_cache,R.id.ll_service})
    public void OnClick(View view){
        switch (view.getId()){
            case R.id.ll_my_avatar:
                checkReadPermission();
                break;
            case R.id.ll_change_phone:
                startActivityForResult(new Intent(SetActivity.this,ChangePhoneActivity.class),36);
//                startActivity(ChangePhoneActivity.class);
                break;
            case R.id.ll_exit:
                setDialog();
                break;
            case R.id.ll_pw_set:
                startActivity(PwSetFirstActivity.class);
                break;
            case R.id.ll_proof_info:
                if ((int)(SP.get(mContext,"ApprovalStatus",0)) == 0) {
                    mContext.startActivity(new Intent(mContext, CertificationInformationActivity.class));
                }else {
                    mContext.startActivity(new Intent(mContext, CertificationInformationStateActivity.class));
                }
                break;
            case R.id.ll_about_app:
                startActivity(AboutAppActivity.class);
                break;
            case R.id.ll_car_term:
                startActivity(CarTeamsActivity.class);
                break;
            case R.id.ll_clear_cache:
                if ("0MB".equals(totalCacheSize)) {
//                    tvClearCache("已清除全部的缓存，请勿重复操作");
                    return;
                }
                new AlertDialog(this).builder().setTitle("确定要清除缓存？")
                        .setPositiveButton("取消", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                            }
                        }).setNegativeButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        DataCleanManager.cleanInternalCache(SetActivity.this);
//                        showToast("已清除" + totalCacheSize + "缓存");
                        totalCacheSize = "0.00MB";
                        tvClearCache.setText(totalCacheSize);
                    }
                }).show();
                break;
            case R.id.ll_service:
                Intent intent = new Intent(this,AboutAppActivity.class);
                intent.putExtra("flag",1);
                startActivity(intent);
                break;

        }
    }

    public void doTakePhoto(){
        PhotoPicker.builder()
                .setPhotoCount(1)
                .setShowCamera(true)
                .setShowGif(false)
                .setPreviewEnabled(false)
                .start(this, PhotoPicker.REQUEST_CODE);
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void checkReadPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            //应用还未获取读取本地文件 的权限，询问是否允许
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 222);
        } else {
            doTakePhoto();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 111) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                checkReadPermission();
            } else {
                showErrorTip("权限被禁止，无法打开相机");
            }
        }else if (requestCode == 222){
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                doTakePhoto();
            } else {
                showErrorTip("权限被禁止，无法打开相机");
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == PhotoPicker.REQUEST_CODE) {
            if (data != null) {
                List<String> list = new ArrayList<>();
                List<String> photos = new ArrayList<>();
                photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                Log.e("photos", photos.get(0).toString());

                Glide.with(this).load(photos.get(0)).into(headImg);
                presenter.uploadImg(photos);

            }
        }else if (requestCode == 36){
            tvChangePhone.setText(SP.get(SetActivity.this,"PhoneNumber","").toString());
        }
    }
    public void setDataView() {
        pickerView = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
//                birthday = date;
//                myBirthday.setText((DateUtil.dateToString(date)));
//                settingUserData();
            }
        })
                .setType(TimePickerView.Type.YEAR_MONTH_DAY)
                .setRange(1900, 2100)
                .build();
        pickerView.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
        pickerView.show();
    }
    public void setDialog(){
        new AlertDialog(mContext).builder().setTitle("确认要退出登录吗?")
                .setPositiveButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                }).setNegativeButton("确定", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                presenter.logOut();
            }
        }).show();
    }

    @Override
    public void AvatarImgSuccess() {
        SP.put(this,"Avatar1",uploadImgBean.getContent().get(0).getRelativePath());
        SP.put(this,"Avatar2",uploadImgBean.getContent().get(0).getMediumThumbnail());
        SP.put(this,"Avatar3",uploadImgBean.getContent().get(0).getSmallThumbnail());
        showShortToast("上传成功");
    }

    @Override
    public void uploadImgSuccess(UploadImgBean uploadImgBean) {
        if (uploadImgBean!=null&&uploadImgBean.getContent()!=null){
            this.uploadImgBean = uploadImgBean;
            imgUrl = uploadImgBean.getContent().get(0).getMediumThumbnail();
            presenter.AvatarImg(SP.get(this,"id","").toString(),uploadImgBean.getContent().get(0).getId());
        }

    }

    @Override
    public void logOutSuccess() {
        startActivity(new Intent(this,MainActivity.class).putExtra("index",1));
        DataCleanManager.cleanSharedPreference(this);
        SP.put(SetActivity.this,"id","");
        finish();
    }

    @Override
    public void getUser(UserBean userBean) {
        if (userBean == null||userBean.getId() == null){

        }else {
            SP.putUser(SetActivity.this, userBean);
        }
        if ((int)SP.get(SetActivity.this,"ApprovalStatus",-2) == -1){
            tvProofType.setText("认证未通过");
        }else if ((int)SP.get(SetActivity.this,"ApprovalStatus",-2) == 0){
            tvProofType.setText("认证未申请");
        }else if ((int)SP.get(SetActivity.this,"ApprovalStatus",-2) == 1){
            tvProofType.setText("认证审核中");
        }else if ((int)SP.get(SetActivity.this,"ApprovalStatus",-2) == 2){
            tvProofType.setText("认证已通过");
        }
        tvChangePhone.setText(SP.get(SetActivity.this,"PhoneNumber","").toString());
        Glide.with(this).load(SP.get(this,"Avatar3","")).error(R.mipmap.head_img).into(headImg);
    }

    @Override
    public void showLoading(String title) {
        startProgressDialog(title);
    }

    @Override
    public void stopLoading() {
        stopProgressDialog();
    }

    @Override
    public void showErrorTip(String msg) {
        if (msg.equals("用户授权失败")){
            msg = "您的登录已失效，请重新登录";
            startActivity(new Intent(this,MainActivity.class).putExtra("index",1));
            finish();
        }
        showShortToast(msg);
    }
}
